package fr.gdi.android.news.api.share;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.android.vending.licensing.LicenseCheckerCallback;

import fr.gdi.android.news.api.AbstractLicensingActivity;
import fr.gdi.android.news.api.R;

public abstract class AbstractShareActivity extends AbstractLicensingActivity implements OnClickListener
{
    private TextView titleView, urlView, shortLinkView, noteView, tagView, sourceView;
    
    private Button shareBtn, cancelBtn; 
    
    private CheckBox shortenCB;
    
    private boolean shorten;
    
    protected boolean initialized = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        checkAccess();
    }
    
    
    
    protected void process()
    {
        setContentView(getLayoutResourceId());  
        titleView = (TextView) findViewById(R.id.title);
        urlView = (TextView) findViewById(R.id.url);
        shortLinkView = (TextView) findViewById(R.id.short_link);
        noteView = (TextView) findViewById(R.id.notes);
        tagView = (TextView) findViewById(R.id.tags);
        sourceView = (TextView) findViewById(R.id.source);
        shareBtn = (Button) findViewById(R.id.share);
        cancelBtn = (Button) findViewById(R.id.cancel);
        
        shortLinkView.setEnabled(false);
        
        urlView.setEnabled(false);
        
        shortenCB = (CheckBox) findViewById(R.id.shortenUrl);
        
        shortenCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton b, boolean checked)
            {
                shortLinkView.setEnabled(checked);
                if ( checked && TextUtils.isEmpty(shortLinkView.getText()) ) 
                {
                    setShortLink();
                }
            }
        });
        
        cancelBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        
        initialized = true;
        
        final Bundle extras = getIntent().getExtras();
        if (extras != null)
        {
            init(extras);
        }
        else
        {
           //TODO: Toast ? 
           finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        if ( initialized && intent.hasExtra("title") ) 
        {
            init(intent.getExtras());
        }
    }
    
    protected void init(final Bundle extras)
    {
        String url = extras.getString("url");
        String title = extras.getString("title");
        
        titleView.setText(title);
        urlView.setText(url);
      
        if ( isShortUrlRequired() ) 
        {
            shorten = false;
            shortenCB.setEnabled(false);
            shortenCB.setChecked(true);
            shortLinkView.setEnabled(false);
            setShortLink(true);
        }
        else
        {
            shorten = false;
            shortenCB.setEnabled(true);
            shortenCB.setChecked(false);
            shortLinkView.setEnabled(true);
            shortLinkView.setText("");
        }
    }

    protected int getLayoutResourceId()
    {
        return R.layout.share_view;
    }
    
    private void setShortLink()
    {
        setShortLink(false);
    }
    
    private void setShortLink(boolean force)
    {
        if ( !force && shorten ) return;
        
        new ShortenUrlTask(this, new IHttpCallback() {
            @Override
            public void execute(String response)
            {
                try
                {
                    shortLinkView.setText(response);
                    shorten = true;
                }
                catch ( Exception e ) 
                {
                    Log.e(AbstractShareActivity.class.getName(), "Caught " + e.getClass().getName() + " while setting shortlink. Ignoring.", e);
                }
            }
        }).execute(getShareUrl().toString());
    }
    
    @Override
    public void onClick(View v)
    {
        if ( v == cancelBtn ) this.finish();
        if ( v == shareBtn ) this.doShare();
    }
    
    private void doShare() 
    {
        CharSequence shortLink = shortLinkView.getText();
        boolean hasShortUrl = !TextUtils.isEmpty(shortLink);
        
        if ( isShortUrlRequired() && !hasShortUrl ) 
        {
            new ShortenUrlTask(this, new IHttpCallback() {
                @Override
                public void execute(String response)
                {
                    share();
                }
            }).execute(getShareUrl().toString());
        }
        else
        {
            share();
        }
    }
    
    protected abstract void share(); 
    
    protected CharSequence getShareTitle() 
    {
        return titleView.getText();
    }
    
    protected CharSequence getShareUrl() 
    {
        CharSequence shortLink = shortLinkView.getText();
        boolean hasShortUrl = !TextUtils.isEmpty(shortLink);
        boolean checked = shortenCB.isChecked();
        return checked && hasShortUrl ? shortLink : urlView.getText(); 
    }
    
    protected CharSequence getShareShortLink() 
    {
        return shortLinkView.getText();
    }
    
    protected CharSequence getShareNotes() 
    {
        return noteView.getText();
    }
    
    protected CharSequence getShareTags() 
    {
        CharSequence tags = tagView.getText();
        return (!TextUtils.isEmpty(tags) ? "# " : "") + tags;
    }
    
    protected CharSequence getShareSource() 
    {
        return sourceView.getText();
    }

    protected String buildMessage()
    {
        String m = getShareTitle() + " - " + 
               getShareNotes() + "\n\n" + 
               getShareUrl() + "\n\n" + 
               getShareTags() + "\n\n" + 
               getShareSource();
        
        int actualMessageLength = m.length();
        if ( actualMessageLength > getMaxMessageLength() ) 
        {
            throw new MessageTooLongException(getMaxMessageLength(), actualMessageLength);
        }
        
        return m;
    }
    
    protected boolean isShortUrlRequired()
    {
        return false;
    }
    
    protected int getMaxMessageLength()
    {
        return Integer.MAX_VALUE;
    }
}
